package dao

import (
	"errors"
	"github.com/liangchao/blogo/src/common/models"
	"github.com/liangchao/blogo/src/common/utils"
)

type CategoryDao struct {
	categories []models.Category
}

// GetCategoryAllList 查询全部分类
func (d *CategoryDao) GetCategoryAllList() (categories []models.Category, err error){
	d.categories, err = new(models.Category).GetCategoryAllList()
	if err != nil {
		return
	}
	categories, err = d.ToMapList()
	return
}

// FindCategoryById 通过 category_id 查找 category
func (d *CategoryDao) FindCategoryById(id int) (category models.Category, err error){
	category.CategoryId = id
	err = category.GetcategoryById()
	if err != nil { return }
	err = d.ToMap(&category)
	return
}

// ToMap 转化为输出数据
func (d *CategoryDao) ToMap(c *models.Category) (err error) {
	if c == nil {
		err = errors.New("input param category is not nil")
		return
	}
	c =  &models.Category{
		CategoryId: c.CategoryId,
		CategoryName: c.CategoryName,
		CategoryIcon: c.CategoryIcon,
		CategoryRank: c.CategoryRank,
		IsDeleted: c.IsDeleted,
		CreateTimeStr: utils.FormatTime(c.CreateTime),
		UpdateTimeStr: utils.FormatTime(c.UpdateTime),
	}

	return
}

// ToMapList 转化为输出数据列表
func (d *CategoryDao) ToMapList() (category []models.Category, err error) {
	if len(d.categories) < 1 {
		err = errors.New("input param c is not nil")
		return
	}

	for i := 0; i < len(d.categories); i++ {
		err = d.ToMap(&d.categories[i])
		if err != nil {return}
	}
	category = d.categories
	return
}